package servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * Servlet implementation class CheckImageServlet
 *
 * 		用于生成验证码的 servlet
 *
 */
@WebServlet( "/image")
//@WebServlet("/image")
public class CheckImageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private final int WIDTH = 120;
	private final int HEIGHT = 30;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		ServletContext context = getServletContext();

		context.getMimeType("aaa.txt");


		// 实现需要在内存中构建一张图片
		BufferedImage br = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);

		//首先 换背景
		// 拿到 可以操作图片的对象
		Graphics2D graphics = (Graphics2D) br.getGraphics();

		//设置 颜色
		graphics.setColor(Color.WHITE);
		//填充颜色
		graphics.fillRect(0, 0, WIDTH, HEIGHT);

		//画个边框, 为蓝色
		graphics.setColor(Color.BLUE);

		graphics.drawRect(0, 0, WIDTH-1, HEIGHT-1);

		String base ="ABCDEFGHIJKLMN";
		Random rand = new Random();

		//画4 个字符上去

		//设置画字符的颜色
		graphics.setColor(Color.RED);
		graphics.setFont(new Font("宋体", Font.BOLD, 18));
		int m =20;


		// 我获验证码的方式是循环四次获取的charAt 我就创建一个字符串缓冲流来储存这些
		StringBuffer sb = new StringBuffer();

		for (int i = 0; i < 4; i++) {

			// 随机取到 一个脚标
			int index = rand.nextInt(base.length());

			char charAt = base.charAt(index);

			// -30 +30

			int jiaodu = rand.nextInt(60)-30;

			double theta = jiaodu*Math.PI/180;

			graphics.rotate(theta,m, 20);   // 旋转
			graphics.drawString(charAt+"", m, 20);
			//charAt+""  这都变成一个字符串了,实质上每个验证码都是一个字符串 我就放心使用字符串缓冲流拼接了,因为是循环得出的,你用一般字符串拼接还写不出来.
			// 将 字符 放到  sb 中
			sb.append(charAt);

			graphics.rotate(-theta,m, 20);

			m+=20;
		}

		//将sb 中 字符 存到 session 中去  //因为都是在一次会话中的
		//字符串缓冲区对象的tostirng方法 就是把缓冲区的数据用字符串表示出来

		request.getSession().setAttribute("checkcode_session", sb.toString());


		//指定线的颜色
		graphics.setColor(Color.GREEN);

		//画 4 条干扰线
		for (int i = 0; i < 4; i++) {

			int x1 = rand.nextInt(WIDTH);
			int x2 = rand.nextInt(WIDTH);
			int y1 = rand.nextInt(HEIGHT);
			int y2 = rand.nextInt(HEIGHT);

			graphics.drawLine(x1, y1, x2, y2);
		}

		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(br, "png", out);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}


}
